#include "VHalLog.h"
#include <stdio.h>
#include <unistd.h>

#define VHAL_LOG_TEMPLATE(LEVEL,TAG)  \
do{ \
    va_list args; \
    va_start(args, format); \
    log(LEVEL, TAG, format, args); \
    va_end(args); \
}while(0)

namespace ecarx::vhal::core {
    thread_local std::string VHalLog::mFileName("");
    thread_local int VHalLog::mLine;
    VHalLog::VHalLog(){
        mLogTag = "EVHAL";
        std::string version = "1.0.0";
#ifdef VHAL_VERSION
        version = VHAL_VERSION;
        if(strcmp(version.c_str(),"") == 0){
            version = "1.0.0";
        }
#endif
        mLogTag.append("(")
            .append(version)
            .append(")");
    }


    void VHalLog::log(int logLevel, const char* tag, const char* format, va_list args){
        char msg[1024];
        vsnprintf(msg, sizeof(msg), format, args);

        std::string printTag = mLogTag;

        if(tag != NULL){
            printTag.append("-").append(tag);
        }
        __android_log_print(logLevel, printTag.c_str(), "[%s:%d] %s\n", mFileName.c_str(), mLine, msg);
    }

    VHalLog& VHalLog::getInstance(const char* fileName, int line){
        static VHalLog sVhalLog;
        mFileName = std::string(fileName);
        mLine = line;
        return sVhalLog;
    }

    void VHalLog::d(const char *format, ...){
        VHAL_LOG_TEMPLATE(ANDROID_LOG_DEBUG, NULL);
    }

    void VHalLog::dTag(const char* tag, const char* format, ...){
        VHAL_LOG_TEMPLATE(ANDROID_LOG_DEBUG, tag);
    }

    void VHalLog::w(const char* format, ...){
        VHAL_LOG_TEMPLATE(ANDROID_LOG_WARN, NULL);
    }

    void VHalLog::wTag(const char* tag, const char* format, ...){
        VHAL_LOG_TEMPLATE(ANDROID_LOG_WARN, tag);
    }

    void VHalLog::e(const char* format, ...){
        VHAL_LOG_TEMPLATE(ANDROID_LOG_ERROR, NULL);
    }

    void VHalLog::eTag(const char* tag, const char* format, ...){
        VHAL_LOG_TEMPLATE(ANDROID_LOG_ERROR, tag);
    }
}//namespace ecarx::vhal::core